/**
 * @author zhangqiang
 * @data 2017/3/14
 *  修改地址
 *
 * * karin 修改 2017/07/14
 * */
import React, {Component} from 'react'
import {List, InputItem, Picker, TextareaItem, Toast, Button, TextInput} from 'antd-mobile';
import {createForm} from 'rc-form';
import Style from './index.scss'
import 'style/addAddress.scss'
import getDataService from '../../services/getData';
import AlipayJSOperation from '../../utils/alipayJSOperation';
import NotExpression from '../../utils/expression';
import PageBar from '../../components/common/pageBar';
import ReModal from '../../components/common/reModal';
import BackMeanSure from '../../utils/backMeanSure';

class ProceDures extends Component {
    constructor(props) {
        super(props);
        this.isDirty = false;
        this.state = {
            name: '',//姓名
            phone: '',//手机号
            district: '', //所在地区 后台数据拼接的省，市，区
            etailedd: '',//详细地区

            regionData: [], //省市区数据
            focused: false,

            provinceName: '', //省份
            provinceCode: '', //省份code
            cityName: '', //城市
            cityCode: '', //城市code
            areaName: '', //所在区
            areaCode: '', //所在区code

            dialogExist: false,//当前是否有弹框出现
        };
        this.orderId = this.props.params.orderId // carId
        this.payTypeData = this.props.params.type // 默认寄送类型.person个人；ems邮政
        this.addressId = this.props.params.addressId
        this.backMeanSureInstance = new BackMeanSure(this.showMeansureBox.bind(this), 'addressEdit');
    }

    showMeansureBox(back, stay) {
        console.log(this.isDirty);
        if (this.isDirty) {
            ReModal.confirm('编辑的信息还未保存，确定现在返回吗？', () => {
                back();
            }, () => {
                stay();
            });
        }
        else {
            back();
        }
    }


    /**
     * 生命周期
     */
    componentWillMount() {
        this.addressViewData();
    }

    componentDidMount() {
        this.backMeanSureInstance.bindBackMeansure();
        document.querySelector("title").innerHTML = "编辑地址";
        getDataService.regionate('').then(data => {
            Toast.hide();
            if (data.code == 1000) {
                this.setState({
                    regionData: data.data.value,
                });
            } else {
                Toast.info(data.msg);
            }
        })
        //隐藏标题栏右键
        AlipayJSOperation.setRightButtonStatus(false);
        //设置标题
        AlipayJSOperation.setTitle('编辑地址');
        //设置标题颜色
        AlipayJSOperation.setBarColor('#2FB3FE');
    }

    componentDidUpdate() {
    }

    componentWillUnmount() {
        AlipayJSOperation.removeLeftButtonEvent();
    }

    /**
     * 事件
     */

    subMit() {//提交表单
        let self = this;
        this.props.form.validateFields((error, value) => {
            //console.log(error, value);

            let telNum = this.state.phone.replace(/\s+/g, ""),
                reg = /^0?1[3|4|5|7丨8][0-9]\d{8}$/,
                reg_name = /^[a-zA-Z\u4e00-\u9fa5\s]{1,20}$/;
            if (!this.state.name && !this.state.phone && !this.state.district && !this.state.etailedd) {
                Toast.info('请填写资料!', 1)
                return false;
            } else {
                if (this.state.name == '' || !this.state.name || this.state.name.replace(/(^\s*)|(\s*$)/g, "") == "") {
                    Toast.info('姓名不能为空!', 1);
                    return false;
                } else if (!reg_name.test(this.state.name)) {
                    Toast.info('姓名格式错误!', 1)
                    return false;
                } else if (NotExpression.isEmojiCharacter(this.state.name.toString())) {
                    Toast.info('姓名不能包含表情!', 1);
                    return false;
                } else if (this.state.phone == '' || !this.state.phone) {
                    Toast.info('手机号码不能为空!', 1);
                    return false;
                } else if (!reg.test(telNum)) {
                    Toast.info('手机格式错误!', 1)
                    return false;
                } else if ((!this.state.district || !this.state.provinceName || !this.state.cityName) && !value.district) {
                    Toast.info('请填写省，市，区(县)!', 1);
                    return false;
                } else if (this.state.etailedd == '' || !this.state.etailedd || this.state.etailedd.replace(/(^\s*)|(\s*$)/g, "") == "") {
                    Toast.info('请填写详细地址!', 1);
                    return false;
                } else if (NotExpression.isEmojiCharacter(this.state.etailedd)) {
                    Toast.info('详细地址不能包含表情!', 1);
                    return false;
                } else if (this.state.etailedd.length < 5) {
                    Toast.info('详细地址长度应不少于5位!', 1);
                    return false;
                }


                let areaCode_s,
                    areaName_s;
                if (!value.district) {  //中山 ，和东莞没有区，和第三级列表
                    areaCode_s = this.state.areaCode;
                    areaName_s = this.state.areaName;
                } else if (value.district.length == 3) {
                    areaCode_s = value.district[2].split(',')[1];
                    areaName_s = value.district[2].split(',')[0];
                } else if (value.district.length == 2) {
                    areaCode_s = '';
                    areaName_s = '';
                }

                let postData = {
                    addressId: this.props.params.addressId,
                    name: this.state.name,
                    phone: this.state.phone,

                    provinceCode: value.district ? value.district[0].split(',')[1] : this.state.provinceCode, //省份code
                    provinceName: value.district ? value.district[0].split(',')[0] : this.state.provinceName, //省份
                    cityCode: value.district ? value.district[1].split(',')[1] : this.state.cityCode,//城市code
                    cityName: value.district ? value.district[1].split(',')[0] : this.state.cityName,//城市
                    areaCode: areaCode_s,//value.district.length==3||value.district?value.district[2].split(',')[1]: value.district?null:this.state.areaCode,//所在区code
                    areaName: areaName_s,//value.district.length==3||value.district?value.district[2].split(',')[0]:value.district?null:this.state.areaName,//所在区

                    location: this.state.etailedd,
                }

                getDataService.addressUpdate(postData).then(data => {
                    Toast.hide();
                    if (data.code == 1000) {
                        Toast.info('保存成功', 1);
                        setTimeout(() => {
                            self.backMeanSureInstance.back()
                        }, 500)
                    } else {
                        Toast.info(data.msg);
                    }
                })

            }
        });
    }

    // 页面加载后,由网址参数，请求车辆信息
    addressViewData() {
        let postData = {
            addressId: this.props.params.addressId
        };
        Toast.hide(); //加载前 先关闭其他加载中的提示框 避免提示框一直存在的bug
        Toast.loading("", 30, () => Toast.info("网络错误", 2));
        getDataService.addressView(postData).then(data => {
            Toast.hide();
            if (data.code == 1000) {
                let data_add = data.data;
                this.setState({
                    name: data_add.name,//姓名
                    phone: data_add.phone,//手机号
                    district: data_add.provinceName + data_add.cityName + data_add.areaName, //所在地区
                    etailedd: data_add.location,//详细地区

                    provinceName: data_add.provinceName, //省份
                    provinceCode: data_add.provinceCode, //省份code
                    cityName: data_add.cityName, //城市
                    cityCode: data_add.cityCode, //城市code
                    areaName: data_add.areaName, //所在区
                    areaCode: data_add.areaCode, //所在区code
                });
                this.isDirty = false;
                /*setTimeout(() => {
                 this.setState({
                 isDirty: false
                 });
                 }, 0)*/

            } else {
                Toast.info(data.msg);
            }
        })

    }

    /*    //清除ant弹框
     closeAliModal() {
     let div = document.querySelector(".am-modal-wrap");
     if (div) {
     div = div.parentNode;
     if (div) {
     div.parentNode.removeChild(div);
     }
     }
     }*/

    deleteCar() { //删除地址
        let self = this;
        if (!this.state.dialogExist) {
            ReModal.confirm('确定要删除此地址吗?', () => {
                Toast.hide(); //加载前 先关闭其他加载中的提示框 避免提示框一直存在的bug
                Toast.loading("", 30, () => Toast.info("网络错误", 2));
                let postData = {
                    addressId: this.props.params.addressId
                };
                getDataService.deleteAddress(postData).then(data => {
                    Toast.hide();
                    if (data.code == 1000) {

                        if (data.data.resultFlag == 1) {
                            //成功
                            if (sessionStorage.getItem('addressId_i') == this.props.params.addressId) {
                                localStorage.removeItem('addressList_action');
                                setTimeout(() => {
                                    try {
                                        self.backMeanSureInstance.back()
                                    }
                                    catch (e) {
                                        alert(JSON.stringify(e));
                                    }
                                }, 300)
                            }

                        } else if (data.data.resultFalg == 0) {
                            //失败
                            Toast.info('删除失败', 1)
                        }

                    } else {
                        Toast.info(data.msg);
                    }
                })
            });

        }
    }

    /**
     * 组件
     */
    render() {

        const {getFieldProps} = this.props.form
        let self = this;
        return (
            <div>
                <div className={Style.proceDures + ' proceDures'}>
                    <PageBar title="编辑地址"/>

                    {/*<div style={{height: '.24rem', backgroundColor: '#f5f5f5',}}></div>*/}
                    <div className={Style.tips}>
                        <div onClick={() => this.deleteCar()}>
                            <img src="./images/update_del.png"/>
                            <span>删除</span>
                        </div>
                    </div>
                    <InputItem
                        style={{width: '100%', color: '#108ee9', textAlign: 'right'}}
                        {...getFieldProps('name') }
                        //clear  不用清楚按钮
                        value={this.state.name}
                        maxLength="12"
                        placeholder="请输入姓名"
                        autoFocus
                        //onBlur ={(e)=>{console.log(e)}}
                        onChange={(name) => {
                            this.setState({
                                name: name,
                            });
                            this.isDirty = true
                        }}
                    >姓名</InputItem>

                    <InputItem
                        style={{width: '100%', color: '#108ee9', textAlign: 'right'}}
                        //clear
                        {...getFieldProps('phone') }
                        type="number" //phone
                        maxLength="11"
                        value={this.state.phone}
                        onChange={(phone) => {
                            this.setState({
                                phone: phone,
                            });
                            this.isDirty = true;
                        }} placeholder="请输入手机号码"
                        // onBlur={(e)=>{this.getPhone(e)}}
                    >联系电话</InputItem>

                    <List style={{backgroundColor: 'white'}} className="picker-list">
                        <Picker extra={this.state.district || "请选择"} data={this.state.regionData}
                                onDismiss={this.onDismiss}
                                format={(values) => {
                                    {
                                        return values.join('');
                                    }
                                }}
                                title="选择地区" {...getFieldProps('district', {
                            onChange() {
                                let extra = document.getElementsByClassName('am-list-extra').innerHTML;
                                self.isDirty = true;
                            },
                        }) }                        >
                            <List.Item arrow="horizontal">所在地区</List.Item>
                        </Picker>
                        <TextareaItem
                            {...getFieldProps('note1') }
                            rows={4}
                            value={this.state.etailedd}
                            onChange={(etailedd) => {
                                this.setState({etailedd: etailedd,});
                                this.isDirty = true;
                            }} placeholder="详细地址"
                            maxLength="60"
                        />
                    </List>

                </div>
                {this.payTypeData == 'ems' && <div className=' color999 plr30 pt30 font-26 text-center'>
                    <span className={Style.iconI}>您选择的邮政上门取件，仅支持广东省内地址</span>
                </div>}

                <Button className={Style.fixedBtn} type="primary" size={'default'}
                        onClick={e => this.subMit()}>保存地址</Button>
            </div>
        )
    }
}

ProceDures.contextTypes = {
    router: React.PropTypes.object.isRequired
};

ProceDures.defaultProps = {}

export default createForm()(ProceDures);
